document.addEventListener('DOMContentLoaded', function() {
    const uploadArea = document.getElementById('upload-area');
    const videoFile = document.getElementById('video-file');
    const uploadProgress = document.getElementById('upload-progress');
    const progressBar = uploadProgress.querySelector('.progress-bar');
    const uploadStatus = document.getElementById('upload-status');
    const videoDetails = document.getElementById('video-details');
    const videoFilename = document.getElementById('video-filename');
    const videoSize = document.getElementById('video-size');
    const videoType = document.getElementById('video-type');
    const cutSettings = document.getElementById('cut-settings');
    const cutInfo = document.getElementById('cut-info');
    const cutError = document.getElementById('cut-error');
    const startCutBtn = document.getElementById('start-cut');
    const clearFormBtn = document.getElementById('clear-form');
    const cutResults = document.getElementById('cut-results');
    const cutFilesList = document.getElementById('cut-files-list');
    const selectAllCheckbox = document.getElementById('select-all-checkbox');
    const downloadSelectedBtn = document.getElementById('download-selected');
    const selectAllBtn = document.getElementById('select-all');

    // 辅助输入框相关
    const quickStartTime = document.getElementById('quick-start-time');
    const quickEndTime = document.getElementById('quick-end-time');
    const quickFileName = document.getElementById('quick-file-name');
    const quickAddBtn = document.getElementById('quick-add-btn');

    let uploadedVideoId = null;

    // 重置页面状态
    function resetPageState() {
        uploadedVideoId = null;
        currentTaskId = null;
        cutInfo.value = '';
        cutError.style.display = 'none';
        cutResults.style.display = 'none';
        cutFilesList.innerHTML = '';
        uploadProgress.style.display = 'none';
        uploadStatus.textContent = '准备上传...';
        progressBar.style.width = '0%';
        startCutBtn.disabled = true;
        startCutBtn.textContent = '开始裁剪';
        clearFormBtn.disabled = true;
        selectAllCheckbox.checked = false;
        videoDetails.style.display = 'none';
        videoFile.value = ''; // 清空文件输入
    }

    // 清空表单
    clearFormBtn.onclick = function() {
        if (confirm('确定要清空当前表单吗？这将清除所有已输入的信息。')) {
            resetPageState();
            cutSettings.style.display = 'none';
        }
    };

    // 处理拖拽上传
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        this.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        this.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        this.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileUpload(files[0]);
        }
    });

    // 处理点击上传
    uploadArea.addEventListener('click', function() {
        videoFile.click();
    });

    videoFile.addEventListener('change', function() {
        if (this.files.length > 0) {
            handleFileUpload(this.files[0]);
        }
    });

    // 处理文件上传
    async function handleFileUpload(file) {
        if (!file.type.startsWith('video/')) {
            alert('请上传视频文件');
            return;
        }

        // 重置页面状态
        resetPageState();

        // 显示视频信息
        videoFilename.textContent = file.name;
        videoSize.textContent = formatFileSize(file.size);
        videoType.textContent = file.type;
        videoDetails.style.display = 'block';

        const formData = new FormData();
        formData.append('video', file);

        try {
            uploadProgress.style.display = 'block';
            uploadStatus.textContent = '正在上传...';
            progressBar.style.width = '0%';

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/api/batch-cut/upload', true);

            // 上传进度
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    const percent = (e.loaded / e.total) * 100;
                    progressBar.style.width = percent + '%';
                }
            };

            // 上传完成
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    uploadedVideoId = response.video_id;
                    uploadStatus.textContent = '上传完成';
                    cutSettings.style.display = 'block';
                    cutError.style.display = 'none';
                    clearFormBtn.disabled = false;
                } else {
                    const error = JSON.parse(xhr.responseText);
                    uploadStatus.textContent = '上传失败: ' + (error.error || '未知错误');
                    videoDetails.style.display = 'none';
                }
            };

            // 上传错误
            xhr.onerror = function() {
                uploadStatus.textContent = '上传失败: 网络错误';
                videoDetails.style.display = 'none';
            };

            xhr.send(formData);
        } catch (error) {
            uploadStatus.textContent = '上传失败: ' + error.message;
            videoDetails.style.display = 'none';
        }
    }

    // 验证裁剪信息
    function validateCutInfo() {
        const lines = cutInfo.value.trim().split('\n');
        const errors = [];
        
        if (lines.length === 0 || (lines.length === 1 && lines[0] === '')) {
            errors.push('请输入裁剪信息');
            return false;
        }

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            if (!line) continue;

            const parts = line.split(/\s+/);
            if (parts.length !== 3) {
                errors.push(`第${i + 1}行格式错误：需要三个参数（开始时间 结束时间 输出文件名）`);
                continue;
            }

            const [startTime, endTime, fileName] = parts;
            
            // 验证时间格式
            const timeRegex = /^(\d{2}):(\d{2}):(\d{2})$/;
            if (!timeRegex.test(startTime) || !timeRegex.test(endTime)) {
                errors.push(`第${i + 1}行时间格式错误：应为HH:MM:SS格式`);
                continue;
            }

            // 验证时间先后
            const startSeconds = timeToSeconds(startTime);
            const endSeconds = timeToSeconds(endTime);
            if (startSeconds >= endSeconds) {
                errors.push(`第${i + 1}行时间错误：开始时间必须早于结束时间`);
                continue;
            }

            // 验证文件名
            if (!fileName || fileName.includes('/') || fileName.includes('\\')) {
                errors.push(`第${i + 1}行文件名错误：文件名不能为空且不能包含路径分隔符`);
                continue;
            }
        }

        if (errors.length > 0) {
            cutError.textContent = errors.join('\n');
            cutError.style.display = 'block';
            startCutBtn.disabled = true;
            return false;
        }

        cutError.style.display = 'none';
        startCutBtn.disabled = false;
        return true;
    }

    // 时间字符串转换为秒数
    function timeToSeconds(timeStr) {
        const [hours, minutes, seconds] = timeStr.split(':').map(Number);
        return hours * 3600 + minutes * 60 + seconds;
    }

    // 监听裁剪信息输入
    cutInfo.oninput = validateCutInfo;

    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'waiting': '待处理',
            'processing': '处理中',
            'success': '已完成',
            'finished': '已完成',
            'error': '失败',
        };
        return statusMap[status] || '待处理';
    }

    // 更新裁剪文件列表
    function updateCutFilesList(files) {
        // 找到第一个未完成且未出错的分段，认为它正在处理中
        let processingIndex = files.findIndex(f => !f.size && !f.error);
        cutFilesList.innerHTML = files.map((file, idx) => {
            let status = file.status;
            if (!status) {
                if (file.error) {
                    status = 'error';
                } else if (file.size) {
                    status = 'finished';
                } else if (idx === processingIndex) {
                    status = 'processing';
                } else {
                    status = 'waiting';
                }
            }
            let progressHtml = '';
            if (status === 'finished') {
                progressHtml = `<span class="text-success">已完成</span>`;
            } else if (status === 'processing') {
                progressHtml = `<div class="d-flex align-items-center" style="height: 24px;"><div class="spinner-border spinner-border-sm text-secondary" role="status" aria-hidden="true"></div></div>`;
            } else {
                progressHtml = `<span class="text-muted">0%</span>`;
            }
            return `
            <tr>
                <td><input type="checkbox" class="file-checkbox" data-file="${file.name}" data-task-id="${file.task_id}" ${status === 'finished' ? '' : 'disabled'}></td>
                <td>${file.name}</td>
                <td>
                    ${progressHtml}
                </td>
                <td>${file.size ? formatFileSize(file.size) : '-'}</td>
                <td>
                    ${status === 'finished' ? 
                        `<button class="btn btn-sm btn-primary download-btn" data-file="${file.name}" data-task-id="${file.task_id}">下载</button>` :
                        ''
                    }
                </td>
            </tr>
            `;
        }).join('');

        // 绑定下载按钮事件
        document.querySelectorAll('.download-btn').forEach(btn => {
            btn.onclick = function() {
                const fileName = this.dataset.file;
                const taskId = this.dataset.taskId;
                window.location.href = `/api/batch-cut/file/${taskId}/${encodeURIComponent(fileName)}`;
            };
        });
    }

    // 单个分段轮询状态
    async function pollSingleTaskStatus(taskId, fileIndex, filesList) {
        while (true) {
            const response = await fetch(`/api/batch-cut/status/${taskId}`);
            const data = await response.json();
            if (data.status === 'finished') {
                // 更新该分段为已完成
                filesList[fileIndex] = {
                    ...filesList[fileIndex],
                    ...data.results[0], // 只处理一个分段
                    status: 'finished',
                    progress: 100
                };
                updateCutFilesList(filesList);
                break;
            } else if (data.status === 'error') {
                // 打印详细日志
                console.error('[裁剪任务失败]', {
                    file: filesList[fileIndex]?.name,
                    status: data.status,
                    backend: data
                });
                filesList[fileIndex].status = 'error';
                updateCutFilesList(filesList);
                break;
            } else {
                // 处理中
                filesList[fileIndex].status = 'processing';
                updateCutFilesList(filesList);
                await new Promise(res => setTimeout(res, 1000));
            }
        }
    }

    // 等待所有任务完成
    async function waitAllTasksFinished(filesList) {
        while (filesList.some(f => f.status !== 'finished')) {
            await new Promise(res => setTimeout(res, 500));
        }
    }

    // 开始裁剪
    startCutBtn.onclick = async function() {
        if (!validateCutInfo() || !uploadedVideoId) return;

        const lines = cutInfo.value.trim().split('\n');
        const cutTasks = lines.map(line => {
            const [startTime, endTime, fileName] = line.trim().split(/\s+/);
            return {
                startTime,
                endTime,
                fileName: fileName + (fileName.endsWith('.mp4') ? '' : '.mp4')
            };
        });

        // 立即显示初始文件列表
        cutResults.style.display = 'block';
        const initialFiles = cutTasks.map(task => ({
            name: task.fileName,
            status: 'waiting',
            progress: 0,
            size: null,
            task_id: null
        }));
        updateCutFilesList(initialFiles);

        // 禁用按钮
        startCutBtn.disabled = true;
        startCutBtn.textContent = '处理中...';
        clearFormBtn.disabled = true;

        for (let i = 0; i < cutTasks.length; i++) {
            const singleTask = [cutTasks[i]];
            const formData = new FormData();
            formData.append('video_id', uploadedVideoId);
            formData.append('tasks', JSON.stringify(singleTask));

            try {
                const response = await fetch('/api/batch-cut', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                if (response.ok) {
                    const taskId = data.task_id;
                    initialFiles[i].task_id = taskId;
                    await pollSingleTaskStatus(taskId, i, initialFiles);
                } else {
                    initialFiles[i].status = 'error';
                    updateCutFilesList(initialFiles);
                    break;
                }
            } catch (error) {
                initialFiles[i].status = 'error';
                updateCutFilesList(initialFiles);
                break;
            }
        }

        // 全部完成
        await waitAllTasksFinished(initialFiles);
        try {
            await fetch(`/api/batch-cut/cleanup/${uploadedVideoId}`, { method: 'POST' });
        } catch (e) {
            // 可以忽略清理失败
        }
        startCutBtn.disabled = false;
        startCutBtn.textContent = '开始裁剪';
        clearFormBtn.disabled = false;
    };

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 全选/取消全选
    selectAllCheckbox.onchange = function() {
        document.querySelectorAll('.file-checkbox').forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    };

    selectAllBtn.onclick = function() {
        selectAllCheckbox.checked = !selectAllCheckbox.checked;
        selectAllCheckbox.dispatchEvent(new Event('change'));
    };

    // 下载选中文件
    downloadSelectedBtn.onclick = function() {
        const selectedFiles = Array.from(document.querySelectorAll('.file-checkbox:checked'))
            .map(checkbox => ({
                name: checkbox.dataset.file,
                task_id: checkbox.dataset.taskId
            }));
        
        if (selectedFiles.length === 0) {
            alert('请选择要下载的文件');
            return;
        }

        // 创建一个隐藏的form来提交下载请求
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/api/batch-cut/download-batch`;
        form.style.display = 'none';

        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'files';
        input.value = JSON.stringify(selectedFiles);
        form.appendChild(input);

        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
    };

    // 辅助输入框相关
    quickAddBtn.onclick = function() {
        const start = quickStartTime.value.trim();
        const end = quickEndTime.value.trim();
        const name = quickFileName.value.trim();
        if (!start || !end || !name) {
            alert('请填写完整的开始时间、结束时间和输出文件名');
            return;
        }
        // 校验时间格式
        const timeRegex = /^(\d{2}):(\d{2}):(\d{2})$/;
        if (!timeRegex.test(start) || !timeRegex.test(end)) {
            alert('时间格式应为 HH:MM:SS');
            return;
        }
        // 校验文件名
        if (name.includes('/') || name.includes('\\')) {
            alert('文件名不能包含路径分隔符');
            return;
        }
        // 拼接一行
        const line = `${start} ${end} ${name}`;
        if (cutInfo.value && !cutInfo.value.endsWith('\n')) {
            cutInfo.value += '\n';
        }
        cutInfo.value += line + '\n';
        // 自动清空输入框
        quickStartTime.value = '';
        quickEndTime.value = '';
        quickFileName.value = '';
        // 触发校验
        validateCutInfo();
        quickStartTime.focus();
    };
});